<?php

/**
 * @author liyi
 * @copyright 2019年1月2日 18:03:03
 * 视觉陷阱
 */

namespace Sjgame\Controller;
use Common\Controller\ApiController;
use function PHPSTORM_META\elementType;

class IndexController extends ApiController {
    
    const GAME_TYPE = 'Sjgame';  // 游戏类型

    const CACHE_KEY = 'sjgames';  // 游戏全局缓存键

    const INVITE = "sjgames:invite"; // 邀请次数

    const SHARE = "sjgames:share"; // 分享次数

    const DBID = 3;

    const DB_USER_NAME = 'sjxj_game.users'; // 游戏用户数据表

    const DB_INVITELOG_NAME = 'sjxj_game.users_invite'; // 游戏邀请数据表

    const IS_REWARD_UID ='sjxj:hint:uid:%s:type:%s'; // 是否领取了提示

    public function __construct()
    {
        parent::__construct();

        $uid = I('id','','int');
        if (!$uid) {
            $this->response(1,'请先登录');
        }
        $this->uid = $uid;
    }

    // 领取奖励提示
    public function getHint() {
        $uid = $this->uid;
        $type = I('type',1,'int'); // 1.免费获取，2.分享获取，3.消耗钻石获取
        $isAeward = sprintf(self::IS_REWARD_UID,$uid,$type);
        $dbId = self::DBID;
        $redis = REDIS('activity');
        $redis->select($dbId);

        $redis->set($isAeward,1);  // 标记
        $redis->exprieAt($isAeward,strtotime(date('Y-m-d 23:59:59'))); // 每日23点59分过期

        $freekey =  sprintf(self::IS_REWARD_UID,$uid,1);
        $sharekey =  sprintf(self::IS_REWARD_UID,$uid,2);
        $expendkey =  sprintf(self::IS_REWARD_UID,$uid,3);

        $free = $redis->get($freekey);
        $share = $redis->get($sharekey);
        $expend = $redis->get($expendkey);

        $data = array('free'=>intval($free),'share'=>intval($share),'expend'=>intval($expend));
        
        $this->response(0,"ok",$data);
    }
 
    // 获取用户邀请
    public function getUserInvite()
    {
        $uid = isset($this->uid)?$this->uid:I('post.id');
        $time = date('Y-m-d');
        $dbname = self::DB_INVITELOG_NAME;
        $dbname2 = self::DB_USER_NAME;

        $list = $this->commUserInvite($uid,$type=1,$dbname,$dbname2,$time);

        $this->response(0,"ok",$list);
    }
    
    // 招人接口(邀请记录接口)
    public function inviteRecord()
    {
        $uid = $this->uid;
        $invite_uid = I('invite_uid',0,'int'); //邀请人用户  10 ,30 50 100
        $type = I('type',1,'int'); // 邀请类型
        $time = date('Y-m-d');
        $dbname = 'sjxj_game.users_invite';  // 数据表
        $cacheKey = self::CACHE_KEY; // 缓存键
        $cacheval = self::INVITE; // 缓存值
        $dbId = self::DBID;

        // 转发邀请记录
        $typeForward = array("101", "102", "103");
        if (in_array($type, $typeForward)) {
            $type_table = 'sj';   // redis表
            $this->getForward($uid, $invite_uid, $type_table, $type);
        }

        $res = $this->commInviteRecord_api($uid,$invite_uid,$type,$time,$dbname,$cacheKey,$cacheval,$dbId);
        if(!empty($res)){
            $this->response(0, "操作成功");
        }else{
            $this->response(1, "操作失败");
        }
    }

    // 招人列表 当天邀请
    public function hiringList() {
        //$uid = $this->uid;
        $uid = isset($this->uid)?$this->uid:I('post.id');
        // 邀请类型 1:每日邀请 2：招募保安  3：招募会计 4：招募经理 5：招募总监  6:金币加速
        $post = I('post.type');  // type[2,3,4,5,6] json数组
        if(!empty($post)){
            if(is_array($post)){
                $type = $post;
            }else{
                $type = json_decode($post,true);
            }
        }else{
            $type=1;
        }

        $sort = I('post.sort'); //
        $dbname = self::DB_INVITELOG_NAME; // 邀请数据表 mining_game.invite_log
        $dbname2 = self::DB_USER_NAME;  //  游戏用户数据表 mining_game.users

        if($type !=99){
            if($sort ==1){
                $time = date('Y-m-d');// 今日邀请
            }else{
                $time = '';// 所有邀请
            }
        }


        $list = $this->commUserInvite_api($uid,$type,$dbname,$dbname2,$time);// 邀请记录
        $info =$temp =array();
        if(!empty($list['userInfo'])) {
            // 按请求类型输出所属信息
            foreach( $list['userInfo'] as $k => $v) {
                $info[$v['type']][] = $v;//所有标识
                unset($temp);
            }
        }

        //$info = array('2'=>$guard,'3'=>$finance,'4'=>$manager,'5'=>$director,'6'=>$speed,'number'=>$list['number']);
        $num = $list['number'];
        $this->response(0, "ok",$info,$num);

    }

    // 邀请记录 - 分享 - 图库
    public function setUnlock()
    {
        $data['uid'] = isset($this->uid)?$this->uid:I('id',0,'int');
        //$data['uid'] = $this->uid;
        $data['imgid'] = I('imgId'); //图片ID
        $data['type'] = I('type',1,'int'); // 邀请类型
        $data['create_time'] = date('Y-m-d');

        if(empty($data['imgid'])){
            $this->response(3, "图片ID不能为空");
        }

        $getUser = M('users_share')->where(array('uid'=>$data['uid'],'imgid'=>$data['imgid']))->find();
        if($getUser){
            $this->response(3, "已经提交过");
        }else{
            $res = M('users_share')->add($data);
            if($res){
                $this->response(0, "操作成功");
            }else{
                $this->response(1, "操作失败");
            }
        }
    }
    
    // 获取用户信息
    public function getUserInfo(){

        $uid = $this->uid;
        $map['id'] = $uid;
        $users = M('users')->where($map)->find();

        $this->response(0,"ok",$users);
    }
    
    // 设置金币
    public function setGold()
    {
        $uid = $this->uid;
        $gold = I('gold','0','string');

        if(!empty($gold)) {
            $data['gold'] = $gold;
        } 

        $map['id'] = $uid;
        $ret = M('users')->where($map)->save($data);
   
        $this->response(0,"操作成功");
    }

    // 游戏入口
    public function gameMain()
    {
    //    $redis = REDIS('activity');
    //    $page = $redis->get('DNPage');
    //    $page = $page ? $page : 1;
    //    $pageNum = 2;
    //    $offset = ($page - 1) * $pageNum;
        
        //$uid = $this->uid;
        $uid = isset($this->uid)?$this->uid:I('post.id');
        //$daily_new_list = array();
        $daily_new_list = C('DAILY_NEW');

        // 每日上新
        $imgs_md5 = array();
 
        //$data['daily_new_list'] = array_slice($daily_new_list,$offset,$pageNum);

        $map['userid'] = $uid;

        /*$pageNum = $this->getJson();   // 视觉陷阱上新配置文件
        $config = M('config')->where('id=1')->getField('num');
        $newNum = $pageNum - $config;
        if($newNum >= 1 && $newNum<=2){
            $save['create_time'] = date('Y-m-d H:i:s');
            $save['num'] = date($pageNum);
            M('config')->where('id=1')->save($save);
            for ( $i=$config;$i<$pageNum;$i++){
                $num = ++$config;
                $imgs = "https://static.bdwha.com/sjxj_game/$num/img.jpg";
                $file_md5 = md5($imgs);
                $daily_new_list[] = array('type'=>'daily','id'=>$num,'img'=>$imgs,'file_md5'=>$file_md5);
            }
        }else{
            $parm = $config+1;
            for ( $i=$config;$i<=$parm ;$i++){
                $num = $config++;
                $imgs = "https://static.bdwha.com/sjxj_game/$num/img.jpg";
                $file_md5 = md5($imgs);
                $daily_new_list[] = array('type'=>'daily','id'=>$num,'img'=>$imgs,'file_md5'=>$file_md5);
            }
        }*/

        $users_game_result  = M('users_game_result')->field('userid,img_url,file_md5')->where($map)->select();
        $imgArr = array();
        if(!empty($users_game_result)) {
            $imgArr = array_column($users_game_result,'file_md5');
        }

        foreach($daily_new_list as $k=>$v) {
            $daily_new_list[$k]['player'] = in_array($v['file_md5'],$imgArr) ? true : false;
        }
 
        // 新手测试
        $new_test_list = C('NEW_TEST');

        foreach($new_test_list as $k1=>$v1) {

            $new_test_list[$k1]['player'] = in_array($v1['file_md5'],$imgArr) ? true : false;
        }
  
        // 分享可解锁
        $share_unlock_list = C('SHARE_UNLOCK');
        $map2['uid'] = $uid;
        $share_unlock_lists = M('users_share')->field('imgId')->where($map2)->select();
        $share = array();
        if(!empty($share_unlock_lists)) {
            $share = array_column($share_unlock_lists,'imgid');
        }

        foreach($share_unlock_list as $k2=>$v2) {
            $share_unlock_list[$k2]['player'] =  in_array($v2['file_md5'],$imgArr)?true:false;
            $share_unlock_list[$k2]['unlock'] =  in_array($v2['id'],$share)?true:false;
        }

        $data = array('daily_new_list'=>$daily_new_list,'new_test_list'=>$new_test_list,'share_unlock_list'=>$share_unlock_list);
        $this->response(0,"ok",$data);
    }


    // 用户图库
    public function gameMain1(){
        $uid = isset($this->uid)?$this->uid:I('post.id');
        $map['userid'] = $uid;
        $img_all_list = array();

        $pageNum = $this->getJson();   // 上新/图库 配置文件
        $config = M('config')->where('id=1')->getField('num');
        if($pageNum > $config){
            $data['num'] = $pageNum;
            M('config')->where('id=1')->save($data);
        }
        $newNum = $pageNum - $config;

        // 图库
        for ( $i=1;$i<=$pageNum;$i++){
            $imgs = "https://static.bdwha.com/sjxj_game/$i/img.jpg";
            $file_md5 = md5($imgs);
            $img_all_list[] = array('id'=>$i,'img'=>$imgs,'file_md5'=>$file_md5);
        }

        // 上新

        $users_game_result  = M('users_game_result')->field('userid,img_url,file_md5')->where($map)->select();
        $imgArr = array();
        if(!empty($users_game_result)) {
            $imgArr = array_column($users_game_result,'file_md5');
        }

        $map2['uid'] = $uid;
        $share_unlock_lists = M('users_share')->field('imgId')->where($map2)->order('id','asc')->select();
        $share = $share_ids  = array();
        if(!empty($share_unlock_lists)) {
            $share = array_column($share_unlock_lists,'imgid');
            $share_ids = array_column($share_unlock_lists,'id');
        }

        foreach($img_all_list as $k2=>$v2) {
            $img_all_list[$k2]['player'] =  in_array($v2['file_md5'],$imgArr)?true:false;   // 游戏成绩状态
            $img_all_list[$k2]['unlock'] =  in_array($v2['id'],$share)?true:false;  // 解锁状态
            // 按解锁先后循序
            if(in_array($v2['id'],$share)){
                $map2['imgid'] = $v2['id'];
                $img_all_list[$k2]['sort'] = M('users_share')->field('imgId')->where($map2)->getField('id');
            }else{
                $img_all_list[$k2]['sort'] = 999;
            }
            array_multisort(array_column($img_all_list,'sort'),SORT_ASC,$img_all_list);
            unset($img_all_list[$k2]['img']);
            unset($img_all_list[$k2]['file_md5']);
        }

        foreach ($img_all_list as $value){
            $data[] = [
                'id'=>$value['id'],
                'player'=>$value['player'],
                'unlock'=>$value['unlock']
            ];
        }

        $this->response(0,"ok",$data);
    }

    
    // 获取图片列表
    public function getImgList()
    {
        $uid = $this->uid;
        $page = I('page',1,'int'); // 页码
        $pageNum = I('pageNum',20,'int'); // 每页数量
        $offset = ($page - 1) * $pageNum;
        
        $map['userid'] = $uid;
  
        $result = M('users_game_result')->where($map)->select();
        
        $this->response(0,"ok",$result);       
        
    }
    
    // 记录游戏成绩
    public function addGameResult()
    {
        $uid = $this->uid;
        $title = I('title','','string');
        $imgUrl = I('imgUrl','','string');
        $directory = I('directory','','string');

        $map['userid'] = $uid;

       if(empty($title)){           
            $this->response(2,"图片标题不能为空");
        }
        if(empty($imgUrl)){
            $this->response(3,"图片地址不能为空");
        }

        $data['userid'] = $uid;
        $data['title'] = $title;
        $data['img_url'] = $imgUrl;
        $data['file_md5'] = md5($imgUrl);
        $data['directory'] = $directory;
        $data['create_time'] = date('Y-m-d H:i:s');

        $new_img = array(1,2,3);    //新手测试
        $share_img = array(4,5,6);  //分享解锁
        $daily_img = array(7,8);    //每日上新
        $new_test_list = C('NEW_TEST');
        $share_unlock_list = C('SHARE_UNLOCK');
        $daily_new_list = C('DAILY_NEW');

        if(in_array($directory,$new_img)){
            foreach($new_test_list as $k2=>$v2) {
                if($v2['id'] == $directory){
                    if($v2['file_md5'] != $data['file_md5']){
                        $this->response(2,"操作失败，新手测试图片不匹配");
                    }
                }
            }
        }else if (in_array($directory,$share_img)){
            foreach($share_unlock_list as $k2=>$v2) {
                if($v2['id'] == $directory){
                    if($v2['file_md5'] != $data['file_md5']){
                        $this->response(2,"操作失败，分享解锁图片不匹配");
                    }
                }
            }
        }else if (in_array($directory,$daily_img)){
            foreach($daily_new_list as $k2=>$v2) {
                if($v2['id'] == $directory){
                    if($v2['file_md5'] != $data['file_md5']){
                        $this->response(2,"操作失败，每日上新图片不匹配");
                    }
                }
            }
        }else{
            $this->response(2,"操作错误，图片不存在");
        }
        $ret = M('users_game_result')->add($data);

        $this->response(0,"操作成功");

    }

    // 获取json配置
    public function getJson()
    {
        //上新最后一个文件夹名（不超过2）
        $url = "/home/wwwroot/static.bdwha.com/sjxj_game/game.json";
        $json_string = file_get_contents($url);
        $info = json_decode(trim($json_string,chr(239).chr(187).chr(191)),true);
        return $info['num'];
    }

    // 每日大礼包（存储）
    public function setGiftData(){

        $uid = isset($this->uid)?$this->uid:I('post.id','','string');  // 用户 openid
        $json = I('post.data'); // Json

        if(empty($uid) || empty($json)){
            $this->response(1, "参数不能为空！");
        }else{
            $goods=htmlspecialchars_decode($json);
            $goods_list=html_entity_decode($goods);
            $data['uid'] = $uid;
            $data['data'] = $goods_list;//转义后
            $data['create_time'] = date('Y-m-d H:i:s');
            $user = M('git')->where(array('uid'=>$uid))->find();

            if($user){
                $res = M('git')->where(array('uid'=>$uid))->save($data);
            }else{
                $res = M('git')->add($data);
            }
            if($res){
                $this->response(0, "ok");
            }else{
                $this->response(2, "大礼包存储失败");
            }

        }


    }

    // 每日大礼包（获取）
    public function getGiftData(){

        $uid = isset($this->uid)?$this->uid:I('post.id');  // 用户ID

        if(empty($uid)){
            $this->response(3, "参数不能为空！");
        }else{
            $data['uid'] = $uid;
            $info = M('git')->field('uid,data')->where($data)->find();
            if(!empty($info)){
                $info['data'] = json_decode($info['data'],true);
            }
            $this->response(0, "ok",$info);
        }
    }

    // 获取服务器当前时间
    public function getServerTime(){
        $time = time();
        $this->response(0, "ok",$time);
    }


    // 定时脚本
    // public function reDNPage()
    // {
    //     $page = I('page','','int');
    //     $redis = REDIS('activity');       
    //     if($page){
    //         $redis->set('DNPage',$page);
    //     }else{
    //         $page = $redis->get('DNPage');
            
    //         if(!$page){
    //             $redis->set('DNPage',1);
    //         }else{
    //             $pageNum = 2;
    //             $offset = ($page - 1) * $pageNum;
                
    //             $count = count(C('DAILY_NEW'));
    //             if($count > ($offset + $pageNum)){
    //                 $redis->set('DNPage',$page + 1);
    //             }            
    //         }            
    //     }
        
    //     $jsons['errno'] = 0;
    //     $jsons['result'] = $redis->get('DNPage');
    //     $this->ajaxReturn($jsons);
    // }
}